
<template>
  <div id="main">
    <h2>员工管理</h2>
    <div class="head">
      <el-button
        type="primary"
        style="margin:20px"
        @click="handleOpen('添加员工', 1)"
      >添加员工</el-button>
      <el-input
        v-model="searchTableInfo"
        placeholder="请输入搜索内容"
        style="width:240px;float: right;margin:20px;"
      />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="staffName" label="员工姓名" />

        <el-table-column align="center" prop="staffId" label="员工编号" />

        <el-table-column align="center" prop="staffJurisdiction" label="员工权限" />

        <el-table-column align="center" prop="staffCall" label="电话" />

        <el-table-column align="center" prop="staffMajor" label="专业" />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleOpen('修改员工', 2, Scope.row.staffId)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(Scope.row.staffId, Scope.row.staffName)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      title=""
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form ref="staff" :model="staff" label-position="top" :rules="rules">
        <el-form-item
          prop="staffName"
          label="姓名"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffName"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="staffSex"
          label="性别"
          :label-width="formLabelWidth"
        >
          <el-radio v-model="staff.staffSex" label="1">男</el-radio>
          <el-radio v-model="staff.staffSex" label="0">女</el-radio>
        </el-form-item>
        <el-form-item
          prop="staffBirth"
          label="出生日期"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="staff.staffBirth"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            format="yyyy 年 MM 月 dd 日"
          />
        </el-form-item>
        <el-form-item
          prop="staffCall"
          label="电话"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffCall"
            maxlength="11"
            autocomplete="off"
            onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
          />
        </el-form-item>
        <el-form-item
          prop="staffEmail"
          label="邮箱"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffEmail"
            autocomplete="off"
            maxlength="32"
          />
        </el-form-item>
        <el-form-item
          prop="staffIdcard"
          label="身份证号"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffIdcard" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffNation"
          label="民族"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffNation" maxlength="20" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffPolitics"
          label="政治面貌"
          :label-width="formLabelWidth"
        >
          <el-select v-model="staff.staffPolitics" placeholder="请选择">
            <el-option
              v-for="item in Pol"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="staffMarry"
          label="婚姻状况"
          :label-width="formLabelWidth"
        >
          <el-radio v-model="staff.staffMarry" label="已婚">已婚</el-radio>
          <el-radio v-model="staff.staffMarry" label="未婚">未婚</el-radio>
        </el-form-item>
        <el-form-item
          prop="staffResidence"
          label="户口所在地"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffResidence" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffLive"
          label="居住地址"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffLive" maxlength="30" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffEdu"
          label="教育程度"
          :label-width="formLabelWidth"
        >
          <el-select v-model="staff.staffEdu" placeholder="请选择">
            <el-option
              v-for="item in Edu"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="staffSchool"
          label="毕业学校"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffSchool" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffMajor"
          label="专业"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffMajor" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffFamily"
          label="家庭成员信息"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffFamily" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="staffContact"
          label="紧急联系方式"
          :label-width="formLabelWidth"
        >
          <el-input v-model="staff.staffContact" autocomplete="off" />
        </el-form-item>
        <el-form-item
          v-if="editType == 1"
          prop="staffGraduationtime"
          label="毕业时间"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="staff.staffGraduationtime"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item
          v-if="editType == 1"
          prop="staffJobresume"
          label="工作履历"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffJobresume"
            autocomplete="off"
            maxlength="500"
            show-word-limit
            type="textarea"
            :autosize="{minRows:2,maxRows:20}"
          />
        </el-form-item>
        <el-form-item
          v-if="editType == 1"
          prop="staffHiredate"
          label="入职时间"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="staff.staffHiredate"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item
          prop="staffDuty"
          label="职务"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffDuty"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="staffTitle"
          label="职称"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffTitle"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="staffRank"
          label="职级"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffRank"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="staffProfession"
          label="专业特长"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffProfession"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="staffTraining"
          label="培训履历"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffTraining"
            autocomplete="off"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          prop="staffWorksummary"
          label="工作总结"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffWorksummary"
            autocomplete="off"
            maxlength="500"
                        show-word-limit
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 20 }"
          />
        </el-form-item>
        <el-form-item
          prop="staffDevelop"
          label="专业发展"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="staff.staffDevelop"
            autocomplete="off"
            maxlength="500"
                        show-word-limit
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 20 }"
          />
        </el-form-item>
        <el-form-item
          prop="staffJurisdiction"
          label="权限等级"
          :label-width="formLabelWidth"
        >
          <el-select v-model="staff.staffJurisdiction" placeholder="请选择">
            <el-option
              v-for="j in jurisdiction"
              :key="j.jurisdictionId"
              :value="j.jurisdictionId"
              :label="j.jurisdictionName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button
          v-if="editType == 2"
          type="primary"
          @click="handleUpdate('staff')"
        >修 改</el-button>
        <el-button
          v-if="editType == 1"
          type="primary"
          @click="handleAddUser('staff')"
        >添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addStaff, deleteStaff, updateStaff, getAllStaff, getStaffById } from '@/api/staff'
import { getAllJurisdiction } from '@/api/jurisdiction'
import { validateChineseName, validateEMail, validatePhone, validateIdNo, validateNation, validateName } from '@/api/validata'
export default {
  data() {
    // var checkphone = (rule, value, callback) => {
    //   // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
    //   if (value == null) {
    //     callback(new Error('员工电话不能为空'))
    //   } else if (!this.isCellPhone(value)) {
    //     // 引入methods中封装的检查手机格式的方法
    //     callback(new Error('请输入正确的手机号!'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      Pol: [{
        value: '选项1',
        label: '中共党员'
      }, {
        value: '选项2',
        label: '中共预备党员'
      }, {
        value: '选项3',
        label: '共青团员'
      }, {
        value: '选项4',
        label: '民革党员'
      }, {
        value: '选项5',
        label: '民盟盟员'
      }, {
        value: '选项6',
        label: '民建会员'
      }, {
        value: '选项7',
        label: '民进会员'
      }, {
        value: '选项8',
        label: '农工党党员'
      }, {
        value: '选项9',
        label: '致公党党员'
      }, {
        value: '选项10',
        label: '九三学社社员'
      }, {
        value: '选项11',
        label: '台盟盟员'
      }, {
        value: '选项12',
        label: '无党派人士'
      }, {
        value: '选项13',
        label: '群众'
      }],
      Edu: [{
        value: '选项1',
        label: '小学'
      }, {
        value: '选项2',
        label: '初中'
      }, {
        value: '选项3',
        label: '中专'
      }, {
        value: '选项4',
        label: '高中'
      }, {
        value: '选项5',
        label: '专科'
      }, {
        value: '选项6',
        label: '本科'
      }, {
        value: '选项7',
        label: '硕士研究生'
      }, {
        value: '选项8',
        label: '博士研究生'
      }, {
        value: '选项9',
        label: '博士后'
      }],
      value: '',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      tableList: [],
      listLoading: false,
      dialogFormVisible: false,
      jurisdiction: [],
      editType: 1, // 1 添加 2 修改
      staff: {},
      newStaff: {
        staffId: '',
        staffName: '',
        staffJurisdiction: ''
      },
      formLabelWidth: '200px',
      searchTableInfo: '',
      rules: {
        staffNation: [
          { required: true, message: '员工民族不能为空', trigger: 'blur' },
          { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffPolitics: [
          { required: true, message: '员工政治面貌不能为空', trigger: 'blur' }
        ],
        staffBirth: [
          { required: true, message: '出生日期不能为空', trigger: 'blur' }
        ],
        staffSex: [
          { required: true, message: '性别不能为空', trigger: 'blur' }
        ],
        staffMarry: [
          { required: true, message: '员工婚姻状况不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffResidence: [
          { required: true, message: '员工户口所在地不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffCall: [
          { required: true, message: '员工电话不能为空', trigger: 'blur' },
          { validator: validatePhone, trigger: ['blur', 'change'] }
        ],
        staffEdu: [
          { required: true, message: '员工教育程度不能为空', trigger: 'blur' }
        ],
        staffEmail: [
          { required: true, message: '员工邮箱不能为空', trigger: 'blur' },
          { validator: validateEMail, trigger: ['blur', 'change'] }
        ],
        staffIdcard: [
          { required: true, message: '员工身份证号不能为空', trigger: 'blur' },
          { validator: validateIdNo, trigger: ['blur', 'change'] }
        ],
        staffJob: [
          { required: true, message: '员工职务不能为空', trigger: 'blur' }
        ],
        staffJurisdiction: [
          { required: true, message: '权限等级不能为空', trigger: 'blur' }
        ],
        staffMajor: [
          { required: true, message: '员工专业不能为空', trigger: 'blur' }
        ],
        staffName: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' },
          { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        // staffSchool: [
        //   { required: true, message: '不能为空', trigger: 'blur' }
        // ],
        staffLive: [
          { required: true, message: '居住地址不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffSchool: [
          { required: true, message: '毕业学校不能为空', trigger: 'blur' },
          { validator: validateName, trigger: ['blur', 'change'] }
        ],
        staffMajor: [
          { required: true, message: '专业不能为空', trigger: 'blur' },
          { validator: validateName, trigger: ['blur', 'change'] }
        ],
        staffFamily: [
          { required: true, message: '家庭成员信息不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffContact: [
          { required: true, message: '紧急联系方式不能为空', trigger: 'blur' },
          { validator: validatePhone, trigger: ['blur', 'change'] }
        ],
        staffJobresume: [
          { required: true, message: '工作履历不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffDuty: [
          { required: true, message: '职务不能为空', trigger: 'blur' }
          // { validator: validateAA, trigger: ['blur', 'change'] }
        ],
        staffTitle: [
          { required: true, message: '职称不能为空', trigger: 'blur' }
          // { validator: validateAA, trigger: ['blur', 'change'] }
        ],
        staffRank: [
          { required: true, message: '职级不能为空', trigger: 'blur' }
          // { validator: validateAA, trigger: ['blur', 'change'] }
        ],
        staffProfession: [
          { required: true, message: '专业特长不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffTraining: [
          { required: true, message: '培训履历不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffWorksummary: [
          { required: true, message: '工作总结不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ],
        staffDevelop: [
          { required: true, message: '专业发展不能为空', trigger: 'blur' }
          // { validator: validateChineseName, trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo
      console.log(this.searchTableInfo)
      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          console.log('success' + data)
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.getAllJurisdiction()
    this.fetchData()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    fetchData() {
      this.tableList = []
      this.listLoading = true
      getAllStaff().then(data => {
        for (var i = 0; i < data.obj.length; i++) {
          this.newStaff.staffId = data.obj[i].staffId
          this.newStaff.staffName = data.obj[i].staffName
          this.newStaff.staffCall = data.obj[i].staffCall
          this.newStaff.staffMajor = data.obj[i].staffMajor
          // this.newStaff.staffJurisdiction = data.obj[i].staffJurisdiction
          if (data.obj[i].staffJurisdiction === 1) {
            this.newStaff.staffJurisdiction = '中心主任'
          }
          if (data.obj[i].staffJurisdiction === 2) {
            this.newStaff.staffJurisdiction = '教务主任'
          }
          if (data.obj[i].staffJurisdiction === 3) {
            this.newStaff.staffJurisdiction = '信息管理'
          }
          if (data.obj[i].staffJurisdiction === 4) {
            this.newStaff.staffJurisdiction = '财务主任'
          }
          if (data.obj[i].staffJurisdiction === 5) {
            this.newStaff.staffJurisdiction = '教学主任'
          }
          if (data.obj[i].staffJurisdiction === 6) {
            this.newStaff.staffJurisdiction = '教学主管'
          }
          if (data.obj[i].staffJurisdiction === 7) {
            this.newStaff.staffJurisdiction = '责任教师'
          }
          if (data.obj[i].staffJurisdiction === 8) {
            this.newStaff.staffJurisdiction = '授课⽼师'
          }
          this.tableList.push(this.newStaff)
          this.newStaff = {}
        }
        this.listLoading = false
      })
    },
    handleDelete(id, username) {
      this.$confirm('确认删除该员工？姓名为' + username).then(() =>
        deleteStaff(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil(
            (this.tableList.length - 1) / this.pagesize
          )
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },
    handleAddUser(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addStaff(this.staff).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.staff = {}
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.staff = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getStaffById(id).then(resp => {
          console.log(resp)
          this.staff = resp.obj
          console.log(this.staff)
        })
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.staff = {}
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.staff)
          updateStaff(this.staff).then(resp => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    getAllJurisdiction() {
      getAllJurisdiction().then(resp => {
        this.jurisdiction = resp.obj
      })
    },
    isCellPhone(val) {
      if (!/^1[3456789]\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    checkEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error('员工邮箱不能为空'))
      } else {
        const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入有效的电子邮箱！'))
        }
      }
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
